package org.example.controller;

import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.anno.Log;
import org.example.pojo.Emp;
import org.example.pojo.LimitPage;
import org.example.pojo.Result;
import org.example.server.EmpServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.List;

@RestController
@Slf4j
public class EmpController {
    @Autowired
    private EmpServer empServer;

    @GetMapping("/emps")
    @Log
    public Result page(String name,Short gender,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize){
        LimitPage lp = empServer.page(name, gender, begin, end, page, pageSize);
        return Result.success(lp);
    }

    @DeleteMapping("/emps/{ids}")
    @Log
    public Result delete(@PathVariable List ids){
        empServer.delete(ids);
        return Result.success();
    }

    @PostMapping("/emps")
    @Log
    public Result add(@RequestBody Emp emp){
        try {
            empServer.add(emp);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加失败,请检查是否重复,或者联系管理员");
        }
    }

    @GetMapping("/emps/{id}")
    @Log
    public Result get(@PathVariable Integer id){
        Emp emp = empServer.getById(id);
        return Result.success(emp);
    }

    @PutMapping("/emps")
    @Log
    public Result update(@RequestBody Emp emp){
        try {
            empServer.update(emp);
            return Result.success();
        } catch (Exception e) {
            return Result.error("更新失败,请检查更新条件是否正确,或者联系管理员");
        }
    }
}
